package com.example.hanfu.zhuanti;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ZhuanTiTask implements Runnable{
    private static final String TAG = "ZhuanTiTask";
    Handler handler;
    private Bitmap bitmap;
    String web_url;

    public ZhuanTiTask(String web_url) {
        this.web_url = web_url;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        Log.i(TAG, "run: ......");
        Document doc = null;
        URL url;
        try {
            doc = Jsoup.connect(web_url).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "doc:" + doc);
        Log.i(TAG, "title:" + doc.title());
        Elements lis = doc.getElementsByClass("ajaxpost");

        Log.i(TAG, "lis=:" + lis);
        List<ZhuanTi> ret = new ArrayList<>();
        List<String> pictures=new ArrayList<>();

        for (Element li : lis) {
            Log.i(TAG, "li=:" + li);
            Element a0 = li.getElementsByTag("a").get(0);
            String title = a0.attr("title");
            String href = a0.attr("href");
            Log.i(TAG, "run:href=" + href);
            Log.i(TAG, "run:title=" + title);

            Bitmap  im[]=new Bitmap[4];
            int i=0;
            Elements imgs=li.getElementsByClass("thumb");
            Log.i(TAG, "run:imgs=" + imgs);
            for(Element img:imgs){
                String img1=img.attr("data-original");
                Log.i(TAG, "run:imgs=" + img1);
                try {
                    url = new URL(img1);
                    InputStream is=url.openStream();
                    bitmap= BitmapFactory.decodeStream(is);
                    im[i]=bitmap;
                    is.close();
                    i++;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //pictures.add(bitmap);
                //Log.i(TAG, "run:img=" + img);
            }
            ret.add(new ZhuanTi(title,href,im[0],im[1],im[2],im[3]));

        }
        Message msg = handler.obtainMessage(1, ret);
        handler.sendMessage(msg);
    }
}
